package cc.cocosky.imclient;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class MainClient extends JFrame implements ActionListener, OnReceiveHandler {
	
	private static final String host = "127.0.0.1";
	private static final int port = 8899;
	
	private JTextArea textArea;
	private JButton connectButton;
	private JTextField inputField;
	private JButton sendButton;
	private SocketInvoker socketInvoker;
	
	public MainClient() {
		setTitle("IM-Test-Client");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		
		textArea = new JTextArea(20, 200);
		panel.add(textArea);
		
		JPanel bottomPanel = new JPanel();
		bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
		
		connectButton = new JButton("Connect");
		connectButton.setActionCommand("Connect");
		connectButton.addActionListener(this);
		bottomPanel.add(connectButton);
		
		inputField = new JTextField();
		bottomPanel.add(inputField);
		
		sendButton = new JButton("Send");
		sendButton.setActionCommand("Send");
		sendButton.addActionListener(this);
		bottomPanel.add(sendButton);
		
		panel.add(bottomPanel);
		
		setBounds(200, 200, 600, 400);
		getContentPane().add(panel);
		setVisible(true);
		
		socketInvoker = new SocketInvoker();
		socketInvoker.setOnReceiveHandler(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String action = e.getActionCommand();
		if("Send".equals(action)) {
			String text = inputField.getText();
			byte[] data = text.getBytes();
			try {
				socketInvoker.send(data);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			textArea.append(text);
			textArea.append("\r\n");
			inputField.setText("");
		} else if("Connect".equals(action)) {
			try {
				socketInvoker.connect(host, port);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			connectButton.setActionCommand("Disconnect");
			connectButton.setText("Disconnect");
		} else if("Disconnect".equals(action)) {
			try {
				socketInvoker.disconnect();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			connectButton.setActionCommand("Connect");
			connectButton.setText("Connect");
		}
	}
	
	@Override
	public void onReceive(byte[] data) {
		String text = new String(data);
		textArea.append(text);
		textArea.append("\r\n");
	}
	
	public static void main(String[] args) {
		new MainClient();
	}


}
